
import json
import pymysql
from pymysql import OperationalError,IntegrityError,ProgrammingError

config = {
    'host': '127.0.0.1',
    'port': 3306,
    'user': 'root',
    'passwd': '123456',
    'db': 'py91',
    'charset': 'utf8'
}


def connect_db():
    try:
        connect = pymysql.connect(**config)
        return connect
    except OperationalError as e:
        print(e)
    except IntegrityError as e:
        print(e)

def write_info(list_info):
    if list_info is None:
        return
    else:
        try:
            commection = connect_db()
            cursor = commection.cursor()
            sql_string = 'insert into douban(name,average,genres)values(%s, %s, %s)'
            cursor.executemany(sql_string,list_info)
            commection.commit()
            print('写入成功！')
        except ProgrammingError as P:
            print(P)
        except IntegrityError as i:
            print(i)
        finally:
            cursor.close()
            commection.close()


def info_list():
    with open('D:/douban.json','r') as f:
        load = json.load(f)
        movie_lise = []
        for item in load['subjects']:
            movie_lise.append((item['title'], item['rating']['average'], ','.join(item['genres'])))
        print(movie_lise)
        return movie_lise

def main():
    movie_list = info_list()
    write_info(movie_list)

if __name__ == '__main__':
    main()


